package com.wk.hooker;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.wk.hooker.login.R;
import com.wk.hooker.util.RefreshLoginActivity;
import android.os.Handler;
import android.widget.Button;
import android.widget.EditText;

import java.io.File;
import java.util.Calendar;
import java.util.List;


/**
 * Created by wuchu on 16/5/19.
 */
public class ClerarWeinXinMsgActivity extends Activity implements View.OnClickListener{


    public final static  String Clear_msg="clear_msg";

    public final static  String  Time ="time";

    public final static  String  fileName="filename";


    private AlarmManager alarm=null;
    private Calendar calendar=Calendar.getInstance();//Calendar是一类可以将时间转化成绝对时间
    //毫秒数的一个类
    private final int HourOfDay=10;//定时更新的小时

    private final int TIME_INTERVAL=1000*60*60*24;//set the interval of the alarm repeating


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clearweixin_main);
        findViewById(R.id.btn_daochu).setOnClickListener(this);
        findViewById(R.id.btn_clear).setOnClickListener(this);

        SharedPreferences pref = getSharedPreferences("weixinok", Context.MODE_WORLD_READABLE);
        EditText editName = (EditText)findViewById(R.id.edit_name);
        editName.setText(pref.getString(fileName,""));



    }


    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.btn_clear:
                SharedPreferences pref = getSharedPreferences("weixinok", Context.MODE_WORLD_READABLE);
                SharedPreferences.Editor editor =pref.edit();
                editor.putInt(Clear_msg,1);
                editor.commit();
                if (!isRunningApp(getApplicationContext(), "com.tencent.mm")) {
                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                    startActivity(intent);
                    getBaseContext().startActivity(intent);
                } else {
                    Intent intent = new Intent(getBaseContext(), RefreshLoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    getBaseContext().startActivity(intent);
                }
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences pref = getSharedPreferences("weixinok", Context.MODE_WORLD_READABLE);
                        SharedPreferences.Editor editor =pref.edit();
                        editor.putInt(Clear_msg,0);
                        editor.commit();
                    }
                },2000);

                break;
            case R.id.btn_daochu:
                saveMsgData();


                break;
        }

    }


    /******
     * 保存清除数据的文件
     */
    private  void saveMsgData(){
        EditText editName = (EditText)findViewById(R.id.edit_name);
        EditText editime  = (EditText)findViewById(R.id.edit_time);
        SharedPreferences pref = getSharedPreferences("weixinok", Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(Time,editime.getEditableText().toString());
        editor.putString(fileName,editName.getEditableText().toString());
        editor.commit();
        setAlarm();
    }


    private void setAlarm(){
        Intent intent=new Intent(this,CleaMsgBroadcast.class);
        //create the Intent between activity and broadcast

        this.alarm=(AlarmManager)super.getSystemService(Context.ALARM_SERVICE);
        //get the alarm service
        this.calendar.set(Calendar.HOUR_OF_DAY,this.HourOfDay);
        //set the hour of the calendar to the value that we want
        this.calendar.set(Calendar.MINUTE, 0);
        //set the minute of the calendar to 0
        this.calendar.set(Calendar.SECOND, 0);
        //set the minute of the calendar to 0
        this.calendar.set(Calendar.MILLISECOND,0);
        //set the millsecond of the calendar to 0


        intent.setAction("org.wkhooker.action.setalarm");//define the action of intent
        PendingIntent sender=PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //define the PendingIntent
        this.alarm.setRepeating(AlarmManager.RTC_WAKEUP, this.calendar.getTimeInMillis(),
                this.TIME_INTERVAL,sender);//set the properties of alarm
        //send broatcast at the same time
    }



    public boolean isRunningApp(Context context, String packageName) {
        boolean isAppRunning = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        for (ActivityManager.RunningTaskInfo info : list) {

            String s = info.baseActivity.getClassName();
            if (info.topActivity.getPackageName().equals(packageName) && (s.contains("LauncherUI"))) {
                isAppRunning = true;
                Log.v("WC", "已经在运行");
                break;
            } else if (info.topActivity.getPackageName().equals(packageName)) {
                break;
            }
        }
        return isAppRunning;
    }



    /*********
     * 获取信息数据库文件的父类的文件名
     * @return
     */
    private String getEmsgName(){
        File file = new File("/data/data/com.tencent.mm/MicroMsg");
        File []files=file.listFiles();
        for(File file1:files){
            if(file1.getName().length()>20&&file1.isDirectory()&&file1.listFiles().length>8){

                return  file1.getName();
            }
        }

        return  null;
    }
}
